#!/bin/bash
set -ex

do_clean_rancherd()
{
    # Check if rancherd exists
    if ! command -v rancherd &> /dev/null
    then
        echo "rancherd not found, no need to uninstall."
    else
        echo "rancherd already exists, starting to clean"
	sudo rm -rf /usr/local/bin/rancherd
        echo "rancherd has been successfully uninstalled."
    fi
}

do_clean_rancherd_service()
{
    if systemctl list-units --full -all | grep -q 'rancherd.service'; then
        echo "rancherd service has found, start to clean it."
        systemctl disable rancherd.service || true
        systemctl reset-failed rancherd.service || true
	rm -rf /etc/systemd/system/rancherd.service
	systemctl daemon-reload
	echo "rancherd service has been successfully uninstalled."

    else
        echo "rancherd service does not exist, no need to clean."
    fi
}

do_clean_rancher_system_agent_service()
{
    if systemctl list-units --full -all | grep -q 'rancher-system-agent.service'; then
        echo "rancher-system-agent service has found, start to clean it."
        systemctl disable rancher-system-agent.service || true
	systemctl reset-failed rancher-system-agent || true
        rm -rf /etc/systemd/system/rancher-system-agent.*
	systemctl daemon-reload
	echo "rancher-system-agent service has been successfully uninstalled."

    else
        echo "rancher-system-agent service does not exist, no need to clean."
    fi
}

do_clean_virtctl()
{
    # Check if virtctl exists
    if ! command -v virtctl &> /dev/null
    then
        echo "virtctl command not found, no need to uninstall."
    else
        echo "virtctl already exists, start to uninstall it."
	rm -rf /usr/bin/virtctl
        echo "virtctl has been successfully uninstalled."
    fi
}

do_clean_wharfie()
{
    # Check if wharfie exists
    if ! command -v wharfie &> /dev/null
    then
        echo "wharfie command not found, no need to uninstall."
    else
        echo "wharfie already exists, start to uninstall it."
	rm -rf /usr/local/bin/wharfie
        echo "wharfie has been successfully uninstalled."
    fi
}


do_clean_rancherd_config_file()
{
    echo "start to clean rancherd config file."
    echo "clean /etc/rancherd/  /var/lib/rancher /usr/share/rancher/rancherd"
    rm -rf /etc/rancher || true
    rm -rf /var/lib/rancher || true
    rm -rf /usr/share/rancher/rancherd || true
    echo "rancherd confie file has been successfully uninstalled."
}

do_uninstall_rke2()
{
    echo "start to clean rancherd config file."
    echo "clean /etc/rancherd/  /var/lib/rancher /usr/share/rancher/rancherd"
    rm -rf /etc/rancher || true
    rm -rf /var/lib/rancher || true
    rm -rf /usr/share/rancher/rancherd || true
    echo "rancherd confie file has been successfully uninstalled."
}

/usr/local/bin/rke2-uninstall.sh
do_clean_rancherd
do_clean_wharfie
do_clean_virtctl
do_clean_rancherd_service
do_clean_rancherd_config_file
